<?php
/**
 * Create by PhpStorm
 * USER: chang
 * Date: 2019/12/17
 * Time：11:37
 * 代理
 */
namespace app\api\controller\v2;

use app\api\controller\User;
use app\common\controller\Api;
use app\admin\model\User as UserModel;
use app\common\model\AgentAdmin;
use app\common\model\AgentShop;
use app\common\model\Goods;
use app\common\model\GoodsSpec;
use app\common\model\ShipOrder;
use think\Db;

class Agent extends Api {
	
	/**
	 * 获取发货下级 (总部发给广东火爆街，提货点; 广东火爆街发给场景店，重庆提货点发货下级场景店）
	 */
	public function getSon() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		$this->area = $this->auth->area;
		
		//检测是否是管理员
		if($level == UserModel::LEVEL_USER) {
			$adminLevel = AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$level = $adminLevel['role'];
				$userId = $adminLevel['user_id'];
			}
		}
		if(!(
			$level == UserModel::LEVEL_HEADQUARTERS ||
			($this->area == UserModel::AREA_SZ && in_array($level, [UserModel::LEVEL_CENTER, UserModel::LEVEL_WAREHOUSE])) ||
			($this->area == UserModel::AREA_OTHER && $level == UserModel::LEVEL_WAREHOUSE)
		)) {
			$this->error('当前帐号没有发货权限', $userId);
		}
		
		$shop = null;
		if($level != UserModel::LEVEL_HEADQUARTERS) {
			$shop = AgentShop::get(['user_id' => $userId]);
			!$shop && $this->error('你没有权限');
		}
		$model = Db::name('agentShop');
		
		$keyword = $this->request->post('keyword');
		if($keyword) {
			$model->where(['name' => ['LIKE', '%'.$keyword.'%']]);
		}
		
		switch ($level) {
			case UserModel::LEVEL_HEADQUARTERS:
				//总部给深圳火爆街，深圳提货点，重庆提货点发货
				$model->where([
					'a.status' => AgentShop::STATUS_Y
				])->where(function($q) {
					$q->whereOr(function($q) {
						$q->where([
							'a.area' => UserModel::AREA_SZ,
							'a.role' => ['in', [UserModel::LEVEL_CENTER, UserModel::LEVEL_WAREHOUSE]]
						]);
					})->whereOr(function($q) {
						$q->where([
							'a.area' => UserModel::AREA_OTHER,
							'a.role' => UserModel::LEVEL_WAREHOUSE,
						]);
					});
				});
				break;
			case UserModel::LEVEL_CENTER:
				$model->where([
					'a.area' => UserModel::AREA_SZ,
					'a.role' => UserModel::LEVEL_SHOP,
					'a.status' => AgentShop::STATUS_Y,
					'a.center_id' => $shop['id']
				]);
				break;
			case UserModel::LEVEL_WAREHOUSE:
				$model->where([
					'a.warehouse_id' => $shop['id'],
					'a.area' => UserModel::AREA_OTHER,
					'a.status' => AgentShop::STATUS_Y
				]);
				break;
			default:
			
		}
		
		$agents = $model->alias('a')
			->join('user u', 'a.user_id = u.id', 'left')
			->field('a.role, a.id, a.name, a.address, u.area, u.reward_number')
			->order(['role' => 'desc', 'name' => 'asc'])
			->select();
		
		if($agents) {
			$roleList = UserModel::$levelList;
			foreach ($agents as &$agent) {
				if($level == UserModel::LEVEL_HEADQUARTERS) {
					$agent['name'] = '【'.$roleList[$agent['role']].'】'.$agent['name'];
					$agent['sign_number'] = Db::name('shipOrder')->where(['sign_agent_id' => $agent['id'], 'status' => ['neq', ShipOrder::STATUS_SUCCESS]])->count();
				}
			}
		}
		
		$this->success('查询成功', $agents);
	}
	
	/**
	 * 在售商品及规格(总部发货使用）
	 */
	public function goodsSpec() {
		$where['status'] = Goods::STATUS_SALE;
		$goods = Db::name('goods')
			->field('id as goods_id, area, name, image')
			->where($where)
			->select();
		if($goods) {
			foreach ($goods as &$good) {
				$good['name'] = ($good['area'] == UserModel::AREA_SZ ? '(深圳)':'').$good['name'];
				$spec = Db::name('goodsSpec')
					->where(['goods_id' => $good['goods_id'], 'status' => GoodsSpec::STATUS_Y])
					->field('id as spec_id, name as spec_name, 0 as number')
					->select();
				
				$good['spec'] = $spec ? : [['spec_name' => '数量', 'number' => 0, 'spec_id' => 0]];
			}
		}
		
		$this->success('查询成功', $goods);
	}
	
	
	/**
	 * 重庆火爆店加入火爆街
	 */
	public function joingWarehouse() {
		$rid = $this->request->post('rid');
		!$rid && $this->error('参数错误');
		$userId = $this->auth->id;
		
		$agent = Db::name('agentShop')->where(['user_id' => $userId, 'status' => AgentShop::STATUS_Y])->find();
		!$agent && $this->error('你不是代理');
		
		if($agent['role'] != UserModel::LEVEL_SHOP || $agent['warehouse_id']) {
			$this->error('你已经有归属火爆街了', $agent);
		}
		
		$rAgent = Db::name('agentShop')
			->where([
				'user_id' => $rid,
				'role' => UserModel::LEVEL_WAREHOUSE,
				'status' => AgentShop::STATUS_Y])
			->find();
		if(!$rAgent) {
			$this->error('你要加入的不是火爆街', Db::name('agentShop')->getLastSql());
		}
		
		$data = [
			'warehouse_id' => $agent ?( $agent['role'] == UserModel::LEVEL_WAREHOUSE ? $agent['id'] : $agent['warehouse_id']) : '',
			'center_id' => $agent ?( $agent['role'] == UserModel::LEVEL_CENTER ? $agent['id'] : $agent['center_id']) : '',
			'theater_id' => $agent ?( $agent['role'] == UserModel::LEVEL_THEATER ? $agent['id'] : $agent['theater_id']) : '',
		];
		
		$res = Db::name('agentShop')
			->where(['id' => $agent['id']])
			->update($data);
		
		if($res) {
			$this->success('加入成功');
		} else {
			$this->error('加入出错');
		}
		
	}
}

